package com.group.itms.routes.activities;

import java.sql.SQLException;
import java.util.ArrayList;
import java.util.List;

import android.content.Context;
import android.content.Intent;
import android.os.Bundle;
import android.support.v4.view.PagerAdapter;
import android.support.v4.view.ViewPager;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.TextView;

import com.actionbarsherlock.view.Menu;
import com.actionbarsherlock.view.MenuItem;
import com.group.itms.routes.R;
import com.group.itms.routes.data.BObject;
import com.group.itms.routes.data.BObjectOption;
import com.group.itms.routes.data.Option;
import com.j256.ormlite.dao.Dao;

public class InfoDetailActivity extends BaseActivity {

	public static final String OPTION_POSITION = "option_position";
	
	private ViewPager mPager;
	private PagerAdapter mPagerAdapter;
	
	private int mOptionPos;
	private BObject mObject;

	public static Intent getIntent(Context c, int objectId, int optionPosition) {
		Intent intent = new Intent(c, InfoDetailActivity.class);
		intent.putExtra(OBJECT_ID, objectId);
		intent.putExtra(OPTION_POSITION, optionPosition);
		return intent;
	}

	@Override
	protected void onCreate(Bundle savedState) {
		super.onCreate(savedState);
		setContentView(R.layout.activity_info_detail);
		init();
		if (savedState != null) {
			// principshi ar ari sachiro ViewPager tviton shoba amas
			mOptionPos = savedState.getInt(OPTION_POSITION);
		}
		
		setTitle(mObject.getName());
	
		mPager = (ViewPager) findViewById(R.id.pager);
		List<Option> opts = mObject.getOptions();
		List<Option> options = new ArrayList<Option>();
		for (Option o : opts) {
			if (o.getName().equalsIgnoreCase("Length") || o.getName().equalsIgnoreCase("Heights")) {
				continue;
			}
			options.add(o);
		}
		mPagerAdapter = new ScreenSlidePagerAdapter(options);
		mPager.setAdapter(mPagerAdapter);
		mPager.setOnPageChangeListener(new ViewPager.SimpleOnPageChangeListener() {

			@Override
			public void onPageSelected(int position) {
				invalidateOptionsMenu();
				mOptionPos = position;
			}
		});
		mPager.setCurrentItem(mOptionPos);
	}

	private void init() {
		Bundle args = getIntent().getExtras();
		if (args == null) {
			throw new RuntimeException(
					"InfoDetailActivity does not have aruments");
		}
		int mLocationId = args.getInt(LocationInfoActivity.OBJECT_ID, -1);
		mOptionPos = args.getInt(OPTION_POSITION);
		
		if (mLocationId == -1) {
			throw new RuntimeException("Missing args with key: " + OBJECT_ID
					+ " to activity: " + getClass());
		}
		mObject = getObject(mLocationId);
		
		if (mObject ==null) {
			throw new RuntimeException("Unable to find Object with id: " + mLocationId);
		}
	}

	@Override
	public boolean onCreateOptionsMenu(Menu menu) {
		getSupportMenuInflater().inflate(R.menu.pager_menu, menu);

		menu.findItem(R.id.action_previous).setEnabled(
				mPager.getCurrentItem() > 0);

		MenuItem item = menu
				.add(Menu.NONE,
						R.id.action_next,
						Menu.NONE,
						(mPager.getCurrentItem() == mPagerAdapter.getCount() - 1) ? R.string.action_finish
								: R.string.action_next);
		item.setShowAsAction(MenuItem.SHOW_AS_ACTION_IF_ROOM
				| MenuItem.SHOW_AS_ACTION_WITH_TEXT);
		return super.onCreateOptionsMenu(menu);
	}

	@Override
	public boolean onOptionsItemSelected(MenuItem item) {
		switch (item.getItemId()) {
		case android.R.id.home:
			goHome();
			break;
		case R.id.action_previous:
			mPager.setCurrentItem(mPager.getCurrentItem() - 1);
			break;

		case R.id.action_next:
			if (item.getTitle().equals(getString(R.string.action_finish))) {
				finish();
			} else {
				mPager.setCurrentItem(mPager.getCurrentItem() + 1);
				break;
			}
		}
		return super.onOptionsItemSelected(item);
	}

	@Override
	protected String getTag() {
		return InfoDetailActivity.class.getSimpleName();
	}

	@Override
	protected void onSaveInstanceState(Bundle outState) {
		super.onSaveInstanceState(outState);
		outState.putInt(OPTION_POSITION, mOptionPos);
	}
	
	private class ScreenSlidePagerAdapter extends PagerAdapter {

		List<Option> mItems = new ArrayList<Option>();
		Dao<BObjectOption, Integer> mOOdao;

		public ScreenSlidePagerAdapter(List<Option> items) {
			mItems = items;
			mOOdao = getHelper().getObjectOptionDao();
		}

		@Override
		public int getCount() {
			return mItems.size();
		}

		@Override
		public Object instantiateItem(ViewGroup container, int position) {
			Context c = InfoDetailActivity.this.getApplicationContext();
			View v = LayoutInflater.from(c).inflate(R.layout.layout_info_detail_pager, null);
			TextView tv = (TextView) v.findViewById(R.id.tvText);
			TextView tittle = (TextView) v.findViewById(R.id.tvTittle);
			
			Option option = mItems.get(position);
			
			tv.setText(getOO(option).getText());
			tittle.setText(option.getName());
			
			((ViewPager) container).addView(v, 0);
			return v;
		}

		private BObjectOption getOO(Option option){
			/// XXX es ar momwons yovel jerze ro bazishi query ketdeba
			List<BObjectOption> objectOptions;
			try {
				objectOptions = mOOdao.queryBuilder().where()
						.eq(BObjectOption.IS_ACTIVE, true)
						.and()
						.eq(BObjectOption.OPTION_COLUMN_NAME, option)
						.and()
						.eq(BObjectOption.BOBJECT_COLUMN_NAME, mObject).query();
			} catch (SQLException e) {
				throw new RuntimeException(e);
			}

			return objectOptions.get(0);
		}
		
		@Override
		public boolean isViewFromObject(View view, Object object) {
			return view == object;
		}
		
		@Override
		public void destroyItem(ViewGroup container, int position, Object object) {
			((ViewPager) container).removeView((View) object);
		}
	}

}
